﻿using Newtonsoft.Json;
using QG.FrontDesk.BLL.IService;
using QG.FrontDesk.com.Attbutes;
using QG.FrontDesk.com.Models;
using QG.FrontDesk.Core;
using QG.FrontDesk.Core.Encrypt;
using QG.FrontDesk.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace QG.FrontDesk.com.Controllers
{
    public class CompanyController : Controller
    {

        private ICompanyService companyService;

        private ICityInfoService cityInfoService;

        private IVerificationCodeService verificationCode;

        private IIndustryService industryService;

        private IDevelopmentPhaseService developmentPhaseService;

        private IVerificationCodeService _verificationCode;
        public CompanyController(ICompanyService companyService, ICityInfoService cityInfoService, IVerificationCodeService codeService, IIndustryService industryService, IDevelopmentPhaseService developmentPhaseService, IVerificationCodeService verificationCode)
        {
            DataContext<Company>.context.model = null;
            DataContext<UserInfo>.context.model = null;
            //获取存在的cookie
            //再次浏览器判断是否有值
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (cookie != null)
            {
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                string userData = ticket.UserData;
                if (ticket.Name == "求职")
                {
                    DataContext<UserInfo>.context.model = JsonConvert.DeserializeObject<UserInfo>(userData);
                }
                else if (ticket.Name == "公司")
                {
                    DataContext<Company>.context.model = JsonConvert.DeserializeObject<Company>(userData);
                }
            }
            this.companyService = companyService;
            this.cityInfoService = cityInfoService;
            this.verificationCode = codeService;
            this.industryService = industryService;
            this.developmentPhaseService = developmentPhaseService;
            _verificationCode = verificationCode;
        }
        //Json返回对象
        ResponseResult result = new ResponseResult();

        /// <summary>
        /// 修改详情页公司信息
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>        
        public JsonResult UpdateCompanyByDetails(Company company)
        {
            DataContext<Company>.context.model.ComForShort = company.ComForShort;//简称
            DataContext<Company>.context.model.OneRecommend = company.OneRecommend;//一句话
            DataContext<Company>.context.model.CompanyLoGo = company.CompanyLoGo;//公司logo
            result.success = companyService.UpdateCompany(DataContext<Company>.context.model) > 0;
            result.data = DataContext<Company>.context.model;
            return Json(result);
        }
        /// <summary>
        /// 修改公司标签
        /// </summary>
        /// <param name="CompId"></param>
        /// <param name="labels"></param>
        /// <returns></returns>
        public JsonResult UpdateLabelaByDetails(int companyId, string labels)
        {
            string[] labelsArry = labels.Split(',');
            result.success = companyService.UpdateLabelaByDetails(companyId, labelsArry) > 0;
            result.data = DataContext<Company>.context.model;
            return Json(result);
        }
        /// <summary>
        /// 修改公司详情页地点,规模,主页
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>
        public JsonResult UpdateCityIndustryByDetails(string CityName, Company company)
        {
            company.CompId = DataContext<Company>.context.model.CompId;
            company.CityInfo = new Cityinfo() { CityName = CityName };//城市
            result.success = companyService.UpdateCityIndustryByDetails(company) > 0;
            result.data = DataContext<Company>.context.model = companyService.GetCompanyInfo(company.CompId);//更新会话
            return Json(result);
        }
        /// <summary>
        /// 修改公司介绍
        /// </summary>
        /// <param name="CityName"></param>
        /// <param name="company"></param>
        /// <returns></returns>
        public JsonResult UpdateCityRemarkByDetails(Company company)
        {
            company.CompId = DataContext<Company>.context.model.CompId;
            result.success = companyService.UpdateCityRemarkByDetails(company) > 0;
            result.data = DataContext<Company>.context.model = companyService.GetCompanyInfo(company.CompId);//更新会话
            return Json(result);
        }
        /// <summary>
        /// 修改公司产品
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>
        public JsonResult UpdateProductByDetails(ProductInfo productInfo)
        {
            productInfo.CompId = DataContext<Company>.context.model.CompId;
            result.success = companyService.UpdateProductByDetails(productInfo) > 0;
            result.data = DataContext<Company>.context.model = companyService.GetCompanyInfo(productInfo.CompId);//更新会话
            return Json(result);
        }

        /// <summary>
        /// 完善公司信息
        /// </summary>
        /// <returns></returns>
        public JsonResult UpdateCompany(Company company)
        {
            company.CompId = DataContext<Company>.context.model.CompId;
            result.success = companyService.UpdateCompany(company) > 0;
            return Json(result);
        }

        /// <summary>
        /// 完善公司标签
        /// </summary>
        /// <param name="labels"></param>
        /// <returns></returns>
        public JsonResult UpdateCompanyTabel(string[] labels)
        {
            int CompId = DataContext<Company>.context.model.CompId;
            result.success = companyService.UpdateCompanyTabel(CompId, labels) > 0;
            return Json(result);
        }
        /// <summary>
        /// 完善公司创始人团队
        /// </summary>
        /// <param name="labels"></param>
        /// <returns></returns>
        public JsonResult UpdateCompanyFound(string teams)
        {
            var CompId = DataContext<Company>.context.model.CompId;
            List<FoundTeam> foundTeams = JsonConvert.DeserializeObject<List<FoundTeam>>(teams);
            foreach (var item in foundTeams)
            {
                item.CompId = CompId;
            }
            //foundTeams.c
            result.success = companyService.UpdateCompanyFound(foundTeams) > 0;
            return Json(result);
        }


        /// <summary>
        /// 完善公司产品信息
        /// </summary>
        /// <param name="teams"></param>
        /// <returns></returns>
        public JsonResult UpdateCompanyProduct(string products)
        {
            var CompId = DataContext<Company>.context.model.CompId;
            List<ProductInfo> productInfos = JsonConvert.DeserializeObject<List<ProductInfo>>(products);
            foreach (var item in productInfos)
            {
                item.CompId = CompId;
            }
            result.success = companyService.UpdateCompanyProduct(productInfos) > 0;
            return Json(result);
        }
        /// <summary>
        /// 完善公司介绍
        /// </summary>
        /// <param name="remark"></param>
        /// <returns></returns>
        public JsonResult UpdateCompanyRemark(string remark)
        {            
            int CompId = DataContext<Company>.context.model.CompId;
            result.success = companyService.UpdateCompanyRemark(CompId, remark) > 0;
            return Json(result);
        }

        /// <summary>
        /// 申请公司验证页面
        /// </summary>
        /// <returns></returns>
        [PermissionAttribute]
        public ActionResult Auth()
        {

            return View();
        }
        /// <summary>
        /// 申请成功
        /// </summary>
        /// <returns></returns>
        public ActionResult AuthSuccess()
        {
            return View();
        }
        ///<summary>
        /// 开启招聘服务--获取邮箱和电话
        /// </summary>
        /// <returns></returns>
        public ActionResult Bindstep1()
        {
            return View();
        }

        /// <summary>
        /// 开启招聘服务-获取公司名称
        /// </summary>
        /// <param name="email"></param>
        /// <param name="tel"></param>
        /// <returns></returns>
        public ActionResult Bindstep2(string email, string tel)
        {
            DataContext<Company>.context.model = new Company();//存到会话里
            DataContext<Company>.context.model.CompanyEmail = email;
            DataContext<Company>.context.model.CompanyPhone = tel;
            return View();
        }

        /// <summary>
        /// 发送邮箱验证
        /// </summary>
        /// <returns></returns>        
        public bool SendEmailCode(string email, string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                code = Guid.NewGuid().ToString();//生成验证码

            }
            Session["code"] = code;//存储验证码
            var mailTo = email;
            email = Encrypt.DESEncrypt(email, "aaaaaaaa");//对邮箱进行加密
            code = Encrypt.DESEncrypt(code, "bbbbbbbb");//对验证码进行加密
            var resultUrl = "https://localhost:44319/Company/GetCodeResult?code=";//返回验证路径
            var mailSubject = DataContext<Company>.context.model.ComFullName + "注册激活";//邮件标题
            var mailContent = "点击链接 <a href ='" + resultUrl + code + "&email=" + email + "'target='_self' >激活" + DataContext<Company>.context.model.ComFullName + "邮箱账号</a >(10分钟内有效) </br>如点击跳转无效,鼠标右键打开链接即可";//邮件内容            
            return EmailHelper.SendEmail(mailTo, mailSubject, mailContent);
        }

        /// <summary>
        /// 开启招聘服务--邮箱发送成功
        /// </summary>
        /// <param name="companyName"></param>
        /// <returns></returns>
        public ActionResult Bindstep3(string companyName)
        {
            if (DataContext<Company>.context.model.CompId == 0)//判断公司是否已完成注册
            {
                DataContext<Company>.context.model.ComFullName = companyName;
                string email = DataContext<Company>.context.model.CompanyEmail;//发送验证信息的邮箱    
                var code = verificationCode.GetCode(email);//如果验证码有效,返回同一验证码
                ViewBag.email = SendEmailCode(email, code) ? email : null;
                if (ViewBag.email != null && code == null)//发送成功并且是全新的验证码,将验证码插入到数据库
                {
                    verificationCode.AddCode(Session["code"].ToString(), email);
                }
            }
            return View();
        }



        /// <summary>
        /// 返回邮箱验证
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult GetCodeResult(string code, string email)
        {
            email = Encrypt.DESDecrypt(email, "aaaaaaaa");//对邮箱进行解密
            code = Encrypt.DESDecrypt(code, "bbbbbbbb");//对验证码进行解密
            VerificationCode verificationCode = new VerificationCode()
            {
                CodeNum = code,
                Email = email,
                LoseTime = DateTime.Now
            };
            //验证成功
            if (Session["code"].ToString() == code || _verificationCode.QueryVerificationCode(verificationCode) > 0)
            {
                //存数据到数据库--返回Id
                int id = companyService.AddCompany(DataContext<Company>.context.model);
                if (id != 0)
                {
                    DataContext<Company>.context.model.CompId = id;
                    return RedirectToAction("Bindstep3", "Company");
                }
            }
            return RedirectToAction("Bindstep1", "Company");
        }
        /// <summary>
        /// 设置密码
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public JsonResult UpdatePwd(string password)
        {
            int compId = DataContext<Company>.context.model.CompId;
            password = MD5Encrypt.Encrypt(password);//加密
            result.success = companyService.UpdatePwd(password, compId) > 0;
            return Json(result);
        }

        /// <summary>
        /// 公司列表页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Companylist(string fs, string ifs, string city, int page = 1)
        {
            List<Cityinfo> cityinfos = cityInfoService.GetCityinfos();
            List<Industry> industries = industryService.GetIndustries();
            List<DevelopmentPhase> developments = developmentPhaseService.GetDevelopmentPhases();
            List<Company> companys = companyService.GetCompanyList(fs, ifs, city);
            ViewBag.developments = developments;
            ViewBag.cityinfos = cityinfos;
            ViewBag.industries = industries;
            ViewBag.Count = companys.Count % 9 > 0 ? companys.Count / 9 + 1 : companys.Count / 10;//总页数
            ViewBag.companys = companys.Skip((page - 1) * 10).Take(9).ToList();//进行筛选分页
            ViewBag.curr = page;//当前页数
            return View();
        }

        /// <summary>
        /// 填写公司信息--基本信息
        /// </summary>
        /// <returns></returns>
        [Permission]
        public ActionResult CompanyInfo1()
        {
            List<Industry> industries = industryService.GetIndustries();
            List<Cityinfo> cityinfos = cityInfoService.GetCityinfos();
            List<DevelopmentPhase> developments = developmentPhaseService.GetDevelopmentPhases();

            ViewBag.industries = industries;
            ViewBag.cityinfos = cityinfos;
            ViewBag.developments = developments;
            ViewBag.company = DataContext<Company>.context.model;//公司

            return View();
        }
        /// <summary>
        /// 填写公司信息--公司标签
        /// </summary>
        /// <returns></returns>
        [Permission]
        public ActionResult CompanyInfo2()
        {
            ViewBag.name = DataContext<Company>.context.model.ComForShort;//公司名
            return View();
        }
        [Permission]
        public ActionResult CompanyInfo3()
        {
            return View();
        }
        [Permission]
        public ActionResult CompanyInfo4()
        {
            return View();
        }
        [Permission]
        public ActionResult CompanyInfo5()
        {
            return View();
        }
        [Permission]
        public ActionResult CompanyInfo6()
        {
            return View();
        }
        /// <summary>
        /// 公司详情(可编辑)
        /// </summary>
        /// <returns></returns>
        [Permission]
        public ActionResult CompanyDetails()
        {
            int Id = DataContext<Company>.context.model.CompId;
            Company company = companyService.GetCompanyInfo(Id) ?? new Company();
            DataContext<Company>.context.model = company;
            ViewBag.company = company;
            return View();
        }
    }
}